import time
from datetime import datetime

from appium.options.android import UiAutomator2Options
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from selenium.common import NoSuchElementException
from selenium.webdriver.ie.webdriver import WebDriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class CommonDriver:
    def get_driver(self):
        # 初始化移动端设备的参数
        options = UiAutomator2Options()
        options.platform_name = 'Android'
        options.platform_version = "7"
        options.app_package = "com.dangdang.buy2"
        # options.app_package = "com.microvirt.launcher2"
        options.app_activity = "com.dangdang.buy2.StartupActivity"
        # options.app_activity = "com.microvirt.launcher.Launcher"
        options.no_reset = False
        options.unicode_keyboard = True
        options.uuid = "127.0.0.1:21513"

        # 设置好appium服务器的url
        command_executor_url = "http://127.0.0.1:4723/wd/hub"

        driver = webdriver.Remote(command_executor=command_executor_url, options=options)

        driver.implicitly_wait(10)

        print("连接成功")

        return driver


if __name__ == '__main__':
    driver = CommonDriver().get_driver()
    # 当脚本直接运行时，创建CommonDriver实例并调用get_driver方法以获取WebDriver
    driver.find_element(AppiumBy.XPATH, '//android.widget.TextView[@text="同意"]').click()
    driver.find_element(AppiumBy.XPATH,
                        '//android.widget.TextView[@resource-id="com.dangdang.buy2:id/tv_sure"]').click()
    driver.find_element(AppiumBy.XPATH,
                        '//android.widget.TextView[@resource-id="com.dangdang.buy2:id/dialog_cancel_tv"]').click()
    driver.find_element(AppiumBy.XPATH,
                        '//android.widget.ViewFlipper[@resource-id="com.dangdang.buy2:id/home_view_flipper"]').click()
    driver.find_element(AppiumBy.XPATH,
                        '//android.widget.EditText[@resource-id="com.dangdang.buy2:id/et_search"]').send_keys("软件测试")
    driver.find_element(AppiumBy.XPATH,
                        '//android.widget.EditText[@resource-id="com.dangdang.buy2:id/et_search"]').clear()
    driver.quit()
